<?php

namespace app\controllers;

use app\models\Supplier;
use app\models\SupplierSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SupplierController implements the CRUD actions for Supplier model.
 */
class SupplierController extends Controller
{
    /**
     * @inheritDoc
     */
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ]
        );
    }

    /**
     * Lists all Supplier models.
     *
     * @return string
     */
    public function actionIndex()
    {
        $searchModel = new SupplierSearch();
        $dataProvider = $searchModel->search($this->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Supplier model.
     * @param int $id ID
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Supplier model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Supplier();

        if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            $model->loadDefaultValues();
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Supplier model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param int $id ID
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Supplier model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param int $id ID
     * @return \yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Supplier model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param int $id ID
     * @return Supplier the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Supplier::findOne(['id' => $id])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    /**
     * 导出全部结果 - 字段选择.
     * 选择后点击确定，下载csv
     * @return string|\yii\web\Response
     */
    public function actionCsv()
    {

        if ($this->request->isPost) {
		//参数接收
		$fields = array_keys($this->request->post("f"));

		//构造查询参数
		$where = [];
		$where_vals = [];
		if($this->request->get("checkall") == 'true'){//全选的情况

			if($this->request->get("id")){
				$where[] = "id=:id"; 
				$where_vals[":id"] = $this->request->get("id");
			}
			if($this->request->get("name")){
				$where[] = "name like :name"; 
				$where_vals[":name"] = '%'.$this->request->get("name").'%';
			}
			if($this->request->get("code")){
				$where[] = "code like :code"; 
				$where_vals[":code"] = '%'.$this->request->get("code").'%';
			}
			if($this->request->get("t_status")){
				$where[] = "t_status=:t_status"; 
				$where_vals[":t_status"] = $this->request->get("t_status");
			}

		}else{//不全选的情况

			//先参数安全过滤
			$ids = explode(",",$this->request->get("ids"));
			foreach((array)$ids as $k=>$v) $ids[$k] = intval($v);

			$where[] = "id in (".implode(",", $ids).")";
		}

		//查询
		$data = Supplier::find()->select($fields)->where(implode(" and ", $where), $where_vals)->asArray()->all();

		//查询结果 转成 csv格式
		$content = [];
		foreach((array)$data as $row){
			if(empty($content)){
				$column_header = [];
				foreach((array)$row as $field=>$value){
					$column_header[] = $field;
				}
				$content[] = implode(",", $column_header);
			}
			$content[] = implode(",", $row);
		}
		$content_csv = implode("\n", $content);

		//输出csv数据
		header("Content-Type: application/vnd.ms-excel; charset=utf-8");
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");
		header("Content-Disposition: attachment;filename=supplier.csv ");
		header("Content-Transfer-Encoding: binary ");
		echo $content_csv;
		exit;

	}

	return $this->render('csv', []);
    }
}
